package com.global.college.views;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatDialogFragment;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;


import com.global.college.R;
import com.global.college.utils.LogUtils;
import com.global.college.utils.ScreenUtils;
import com.global.college.utils.ToastUtils;
import com.global.college.utils.UiUtils;
import com.global.college.widget.picker.photo_picker.HnPhotoUtils;

import java.io.FileNotFoundException;

import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 头像编辑
 */
public class HnEditHeaderDialog extends AppCompatDialogFragment {
    private static final String[] permissions = {
            Manifest.permission.CAMERA
    };

    private static HnEditHeaderDialog sDialog;
    private AlertDialog dialog;
    private Activity mActivity;
    private Uri mTempPhotoUri;
    private Uri mCroppedPhotoUri;
    private float mWidth = 160.0f;
    private float mHeight = 160.0f;
    private static final int REQUEST_CODE_CAMERA_PHOTO = 1001;
    private static final int REQUEST_CODE_PICKED_PHOTO = 1002;
    private static final int REQUEST_CODE_CROP_PHOTO = 1003;
    private String TAG = "HnEditHeaderDialog";

    public static HnEditHeaderDialog newInstance() {

        Bundle args = new Bundle();
        sDialog = new HnEditHeaderDialog();
        sDialog.setArguments(args);
        return sDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();

        mTempPhotoUri = HnPhotoUtils.generateTempImageUri(mActivity);
        mCroppedPhotoUri = HnPhotoUtils.generateTempCroppedImageUri(mActivity);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        View view = View.inflate(mActivity, R.layout.dialog_edit_header, null);

        ButterKnife.bind(this, view);
        Dialog dialog = new Dialog(mActivity, R.style.PXDialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window alertWindow = dialog.getWindow();
        alertWindow.setGravity(Gravity.BOTTOM);

        WindowManager.LayoutParams params = alertWindow.getAttributes();
        params.width = mActivity.getWindowManager().getDefaultDisplay().getWidth();
        params.height = ScreenUtils.dp2px(mActivity, 200.0f);
        alertWindow.setAttributes(params);

        return dialog;
    }


    @OnClick({R.id.tv_cancel, R.id.tv_take_photo, R.id.iv_take_photo, R.id.tv_galley, R.id.iv_galley})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                dialogDismiss();
                break;
            case R.id.tv_take_photo:  //拍照
            case R.id.iv_take_photo:  //拍照
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求
                        showDialogTipUserRequestPermission();
                    } else {

                        final Intent intentCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        HnPhotoUtils.addPhotoPickerExtras(intentCapture, mTempPhotoUri);
                        startActivityForResult(intentCapture, REQUEST_CODE_CAMERA_PHOTO);
                    }
                } else if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {

                    final Intent intentCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    HnPhotoUtils.addPhotoPickerExtras(intentCapture, mTempPhotoUri);
                    startActivityForResult(intentCapture, REQUEST_CODE_CAMERA_PHOTO);
                }

                break;

            case R.id.tv_galley:  //相册
            case R.id.iv_galley:  //相册

                final Intent intentPick = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                HnPhotoUtils.addPhotoPickerExtras(intentPick, mTempPhotoUri);
                if (intentPick.resolveActivity(mActivity.getPackageManager()) != null) {
                    startActivityForResult(intentPick, REQUEST_CODE_PICKED_PHOTO);
                } else {
                    ToastUtils.showCenterToast(R.string.can_not_find_the_application);
                }

                break;
        }
    }

    /**
     * dialog消失
     */
    private void dialogDismiss() {
        if (sDialog != null) {
            sDialog.dismiss();
            sDialog = null;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 123) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(mActivity, R.string.get_the_permission_success, Toast.LENGTH_SHORT).show();

                    final Intent intentCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    HnPhotoUtils.addPhotoPickerExtras(intentCapture, mTempPhotoUri);
                    startActivityForResult(intentCapture, REQUEST_CODE_CAMERA_PHOTO);
                }
            }
        }

        if (resultCode == Activity.RESULT_OK) {

            switch (requestCode) {
                // Cropped photo was returned
                case REQUEST_CODE_CROP_PHOTO: {

                    if (getDialog().isShowing()) {
                        getDialog().dismiss();
                    }
                    final Uri uri;
                    if (data != null && data.getData() != null) {
                        uri = data.getData();
                    } else {
                        uri = mCroppedPhotoUri;
                    }
                    try {
                        // delete the original temporary photo if it exists
                        mActivity.getContentResolver().delete(mTempPhotoUri, null, null);
                        Bitmap bitmap = HnPhotoUtils.getBitmapFromUri(mActivity, uri);
                        if (onImageCallBack != null) {
                            onImageCallBack.onImage(bitmap, uri);
                        }

                    } catch (FileNotFoundException e) {
                        Toast.makeText(mActivity, R.string.not_find_file, Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                case REQUEST_CODE_PICKED_PHOTO:
                case REQUEST_CODE_CAMERA_PHOTO:
                    final Uri uri;
                    boolean isWritable = false;
                    if (data != null && data.getData() != null) {
                        uri = data.getData();
                        LogUtils.d("<<", "uri=" + data.getData());
                    } else {
                        uri = mTempPhotoUri;
                        isWritable = true;
                    }
                    final Uri toCrop;
                    if (isWritable) {
                        toCrop = uri;
                    } else {
                        toCrop = mTempPhotoUri;
                        try {
                            HnPhotoUtils.savePhotoFromUriToUri(mActivity, uri,
                                    toCrop, false);
                        } catch (SecurityException e) {
                            LogUtils.d(TAG, "Did not have read-access to uri : " + uri);
                        }
                    }

                    doCropPhoto(toCrop, mCroppedPhotoUri);
                    break;
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            if (getDialog().isShowing()) {
                getDialog().dismiss();
            }
        }
//        dialogDismiss();
    }
    /**
     * 调用系统裁剪
     */
    private void doCropPhoto(Uri inputUri, Uri outputUri) {
        try {
            final Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(inputUri, "image/*");
            HnPhotoUtils.addPhotoPickerExtras(intent, outputUri);
            HnPhotoUtils.addCropExtras(intent, ScreenUtils.dp2px(mActivity, mWidth), ScreenUtils.dp2px(mActivity, mHeight));
            startActivityForResult(intent, REQUEST_CODE_CROP_PHOTO);
        } catch (Exception e) {
            Toast.makeText(mActivity, UiUtils.getString(R.string.not_find_img), Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 对外提供图片设置接口
     */
    public interface OnImageCallBack {
        void onImage(Bitmap bitmap, Uri uri);
    }

    private OnImageCallBack onImageCallBack;

    public void setOnImageCallBack(OnImageCallBack onImageCallBack) {
        this.onImageCallBack = onImageCallBack;
    }


    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(mActivity, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults.length > 0) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                        boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                        if (!b) {
                            // 用户还是想用我的 APP 的
                            // 提示用户去应用设置界面手动开启权限
                            showDialogTipUserGoToAppSettting();
                        } else {
                            showDialogTipUserRequestPermission();
                        }

                        ToastUtils.showCenterToast(R.string.please_access_perssion);
                    } else {
                        Toast.makeText(mActivity, R.string.get_the_permission_success, Toast.LENGTH_SHORT).show();
                        final Intent intentCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        HnPhotoUtils.addPhotoPickerExtras(intentCapture, mTempPhotoUri);
                        startActivityForResult(intentCapture, REQUEST_CODE_CAMERA_PHOTO);

                    }
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting() {
        dialog = new AlertDialog.Builder(mActivity)
                .setTitle(R.string.permission_not_use)
                .setMessage(R.string.permission_start_tip_info)
                .setPositiveButton(R.string.permission_to_start, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                        //showDialogTipUserRequestPermission();
                    }
                })
                .setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ToastUtils.showCenterToast(R.string.please_access_perssion);
                        return;
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }


    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {
//        new AlertDialog.Builder(this)
//                .setTitle("相机权限、读写权限")
//                .setMessage("由于需要摄像，需要开启相机权限\n" +
//                        "存储文件，需要开启读写权限\n" +
//                        "否则无法正常使用")
//                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
        startRequestPermission();
//                    }
//                })
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        ToastUtils.showCenterToast("请允许权限开启");
//                        finish();
//                    }
//                }).setCancelable(false).show();
    }
}
